import axios from 'axios'
import { useUserStore } from '@/stores'
import { ElMessage } from 'element-plus'
import { oAuthTokenRefreshToken } from '@/api/oAuth.js'
import router from '@/router'

const baseURL = 'http://localhost:88'

const instance = axios.create({
  baseURL,
  timeout: 10000
})

instance.interceptors.request.use(
  async config => {
    const useStore = useUserStore()
    if (useStore.token !== '') {
      config.headers.Authorization = `Bearer ${useStore.token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

const refreshToken = async (email, token) => {
  try {
    const response = await oAuthTokenRefreshToken(email, token)
    const useStore = useUserStore()
    await useStore.refreshTokenInfo(response.data.token, response.data.type, response.data.expires)
  } catch (error) {
    console.error(error)
  }
}

instance.interceptors.response.use(
  response => {
    if (response.data.code === 200) {
      return response.data
    }
    ElMessage.error(response.data.message || '服务异常')
    return Promise.reject(response.data)
  },
  error => {
    if (error.response?.status === 401) {
      if (error.response.data.message === 'token 无效或过期') {
        const useStore = useUserStore()
        useStore.removeFullInfos()
        router.push('/')
      }
    }
    if (error.response?.status === 403) {
      ElMessage.error(error.response.data.message)
    }
    ElMessage.error(error.response.data.message || '服务异常')
    return Promise.reject(error)
  }
)

export default instance
export { baseURL }
